import time
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.wait import WebDriverWait


# 设置Chrome选项
chrome_options = Options()
# chrome_options.add_argument('--headless')  # 无头模式
chrome_options.add_argument('--disable-gpu')

# 添加试验性参数
chrome_options.add_experimental_option('excludeSwitches', ['enable-automation'])
chrome_options.add_experimental_option('useAutomationExtension', False)

chrome_options.add_argument("--disable-blink-features")
chrome_options.add_argument("--disable-blink-features=AutomationControlled")

#远程调试浏览器
# chrome_options.add_experimental_option('debuggerAddress', '127.0.0.1:9222')

user_agent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36"
chrome_options.add_argument('--user-agent=%s' % user_agent)

# 设置ChromeDriver路径
service = Service('D:/chromedriver-win64/chromedriver.exe')

# 启动浏览器
driver = webdriver.Chrome(service=service, options=chrome_options)
driver.execute_cdp_cmd("Page.addScriptToEvaluateOnNewDocument", {
    "source": """
    Object.defineProperty(navigator, 'webdriver', {
      get: () => undefined
    })
  """
})


# 1688商品详情页面的URL
url = 'https://www.alibaba.com/product-detail/20-Years-GPS-manufacturer-COBAN-factory_1601097441698.html?spm=a2700.galleryofferlist.topad_classic.d_image.146d2b3aSh41nq'
# 访问页面
driver.get(url)
# 设置浏览器：driver  等待时间：20s
# wait = WebDriverWait(driver, 20)
# 设置隐式等待时间为10秒
driver.implicitly_wait(10)

html = driver.find_element(By.CSS_SELECTOR,"html").text
print(html)
# 获取商品标题
try:
    title = driver.find_element(By.CSS_SELECTOR, 'h1.d-title').text
    print(f'商品标题: {title}')
except:
    print('未能找到商品标题')

# 获取商品价格
try:
    price = driver.find_element(By.CSS_SELECTOR, 'span#j-sku-price').text
    print(f'商品价格: {price}')
except:
    print('未能找到商品价格')

# 获取商品描述
try:
    description = driver.find_element(By.CSS_SELECTOR, 'div#mod-detail-description').text
    print(f'商品描述: {description}')
except:
    print('未能找到商品描述')


# driver.implicitly_wait(30)
# 关闭浏览器
driver.quit()
